// pages/farmer/info/index.js
var app = getApp(), fetchApi = require("../../../utils/httpPost.js"),
formatTime = require("../../../component/common.js")
import Dialog from '../../../component/vant/dialog/dialog';
import Toast from '../../../component/vant/toast/toast';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pageIndex:1,
    pageSize:10,
    feed_state:0,//喂食状态 0 - 未喂食 1 - 吃食中
    friendList:[],//我的好友
    poultry:{},//小鸡信息
    farm:{},//农场信息
    feed:{},//饲料厂信息
    is_poultry:0,//是否存在领养小鸡  0 - 未领养  1-  已领养
    dayOrNight:0,//当前时间段在白天还是晚上
    background:"https://img.sdyuedou.com/farmer/index1Bg.gif",
    eggPosition:[
      {left:24, top: -6},
      {left:60, top: -6},
      {left:100, top: -6},
      {left:20, top: 23},
      {left:60, top: 23},
      {left:100, top: 23},
    ],
    rubers_count:0,//蹭友数量
    rubers:[],//蹭友列表
    chickensPosition:[
      {left:'unset', top: '80rpx',right:'166rpx'},
      {left:'unset', top: '250rpx',right:'290rpx'},
      {left:'unset', top: '250rpx',right:'60rpx'},
    ],
    farmUserId:0,
    feedCount:0,// 可用余粮
    eggCount:0,
    ticketCount:0,
    ownerName:'',
    ydCount:0,
    isShowExchangeYd:false,
    exchangeEggCount:1,
    showTransition:false,
    nameTransition:'fade',
    is_my:0,
    my_eat_state:0,//我自己的小鸡 吃食的状态 
    my_rub_state:0,//我自己的小鸡 是否在外溜达
    transitionLeft:0,
    transitionTop:0,
    transitionCss:'block_0',
    pickRubPoultryId:0,
    clickMy:false,
    scores:[],
    isLogin:0,
    ag_id:0,
    feedWeight:100,//每次投喂的克重数
    toFarmUserId:0,
    isiphonex: app.globalData.isiphonex,
    isxiaomi: app.globalData.isxiaomi,
    crops:[],
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('农场接收参数',options)
    if(options.ag_id){
      this.data.ag_id = parseInt(options.ad_id);
      this.setData({
        ag_id: this.data.ag_id,
      })
    }

    // this.data.farmUserId = app.globalData.to_farm_user_id;
    if(options.userId){
      this.data.farmUserId = parseInt(options.userId);
      this.setData({
        farmUserId: parseInt(options.userId)
      })
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (options) {
    var isLogin = app.getStorageSync("isLogin");
    this.setData({
      isLogin : isLogin
    })

    console.log('onShow================')
    var isLogin = app.getStorageSync("isLogin");
    if(isLogin == 0){
      if(this.data.ag_id > 0){
        wx.navigateTo({
          url: '/pages/login/index?ag_id=' + this.data.ag_id,
        })
      }else{
        wx.navigateTo({
          url: '/pages/login/index',
        })
      }
    }else{
      this.data.pageIndex = 1;
      this.setData({
        friendList:[]
      })
      this.onHttpInit();
    }
  },
  /**
   *  获取附近的人的用户列表
   */
  onHttpInit: function () {
    var that = this;
    fetchApi.httpPost('/farm/info', {
      farmUserId:this.data.farmUserId
    }, function (res) {
      console.log("获取农场信息", res)
      if (res.data.code == 0) {
        that.data.farm = res.data.data.farm;
        console.log('farm',that.data.farm)
        console.log('ownerName',res.data.data.ownerName)
        
        that.setData({
          poultry: res.data.data.poultry,
          farm: res.data.data.farm,
          eggCount: res.data.data.farm.eggsCount > 6 ? 6 : res.data.data.farm.eggsCount,
          feed: res.data.data.feed,
          feedCount: res.data.data.feed.feedCount,
          ticketCount: res.data.data.ticketCount,
          feed_state:res.data.data.farm.eatState,
          is_poultry: res.data.data.is_poultry,
          dayOrNight: res.data.data.dayOrNight,
          rubers: res.data.data.rubers,
          rubers_count: res.data.data.rubers_count,
          watchAdDetailSecond: res.data.data.watchAdDetailSecond,
          // inviteFriendCount: res.data.data.inviteFriendCount,
          watchAdDetailMaxCount: res.data.data.watchAdDetailMaxCount,
          watchAdDetailFeedCount: res.data.data.watchAdDetailFeedCount, 
          feedWeight:res.data.data.feedWeight, 
          buyFeedCount: res.data.data.buyFeedCount,
          ownerName:res.data.data.ownerName,
          ydCount:res.data.data.ydCount,
          crops:res.data.data.crops,
          background:res.data.data.dayOrNight == 0 ? "https://img.sdyuedou.com/farmer/index1Bg.gif" 
          : "https://img.sdyuedou.com/farmer/index2Bg.gif"
        })
        that.data.is_my = res.data.data.is_my;
        if(res.data.data.is_my == 0){
          that.data.my_eat_state = res.data.data.my_eat_state
          that.data.my_rub_state = res.data.data.my_rub_state
          that.setData({
            my_eat_state:res.data.data.my_eat_state,
            my_rub_state:res.data.data.my_rub_state,
          })
        }
      }else{
        // Toast.fail(res.data.msg)
      }
      that.setData({ netWork: true, isLoading: false, })
    }, function () {
      that.setData({ netWork: false, hasData: false, isLoading: false, })
    })
  },
  //左上角返回按钮
  goBack(){
    wx.navigateBack({
      delta: -1,
    })
  },
  //去喂食
  goWeiShi(e){
    var that = this;
    var isLogin = app.getStorageSync("isLogin");
    if (!isLogin) {
      wx.navigateTo({
        url: '/pages/login/index?ag_id=' + this.data.ag_id,
      })
    }else{
      console.log('goWeiShi',e)
      if(that.data.is_my == 0){
        Toast.fail("暂未开放给好友投喂饲料哟~")
      }else{
        this.onHttpFeed();
      }
    }
  },
  //请走其他人的小鸡
  goDriveOp(e){
    console.log('goDriveOp',e);
    var type = e.currentTarget.dataset.type;
    this.onHttpDriveOp(type)
  },
  onHttpDriveOp(type){
    var that = this;
    fetchApi.httpPost('/farm/goDriveOp', {
      farm_id: that.data.farm.id,
      ruber_poultry_id:that.data.pickRubPoultryId
    }, function (res) {
      console.log("去遛弯蹭吃", res)
      if (res.data.code == 0) {
        if(type == 0){
          Toast.success(res.data.msg);
          that.setData({
            feed_state:res.data.data.farm.eatState,
            is_poultry: res.data.data.is_poultry,
            rubers: res.data.data.rubers,
            rubers_count: res.data.data.rubers_count,
          })
        }else{
          wx.navigateBack({
            delta: -1,
          })
        }
      }else{
        Toast.fail(res.data.msg);
      }
    }, function () {})
  },
  /**
   *  喂食操作
   */
  onHttpFeed() {
    var that = this;
    fetchApi.httpPost('/farm/eatFeed', {
      farm_id: that.data.farm.id,
    }, function (res) {
      console.log("喂食响应", res)
      if (res.data.code == 0) {
        that.setData({feed_state : 1})
        console.log('that.data.farm',that.data.farm)
        that.data.farm.overTime = res.data.data.overTime;
        
        // farm.overTime
        console.log('that.data.farm.overTime',that.data.farm.overTime)
        that.data.farm.bowlWeight = res.data.data.bowlWeight;
        that.setData({
          feedCount: res.data.data.leftFeedCount,
          farm: that.data.farm
        })
        Toast.success(res.data.msg);
      }else{
        Toast.fail(res.data.msg);
      }
    }, function () { })
  },
  /**
   *  蹭吃
   */
  goCengChi(){
    var that = this;
    console.log('goCengChi')
    console.log('my_eat_state',this.data.my_eat_state)
    var message = "小鸡正在享受的吃美食中，确定要让它遛弯吗？";
    // var 
    if(this.data.my_eat_state == 1){
      Dialog.confirm({
        title: '去遛弯',
        message
      }).then(() => {
        that.onHttpCengChi()
      })
      .catch(() => {
        Dialog.close();
      });
    }else{
      that.onHttpCengChi()
    }
  },
  onHttpCengChi(){
    var that = this;
    fetchApi.httpPost('/farm/goWalk', {
      other_farm_id: that.data.farm.id,
    }, function (res) {
      console.log("去遛弯蹭吃", res)
      if (res.data.code == 0) {
        Toast.success(res.data.msg);
        that.setData({
          feed_state:res.data.data.farm.eatState,
          is_poultry: res.data.data.is_poultry,
          rubers: res.data.data.rubers,
          rubers_count: res.data.data.rubers_count,
        })
      }else{
        Toast.fail(res.data.msg);
      }
    }, function () {})
  },
  //点击小鸡的事件
  onClickCustom(e) {
    console.log('onClickCustom',e)
    var index = e.currentTarget.dataset.index ;
    console.log('userid',userid)
    console.log('farm userid',this.data.farm.userId)
    
    var css = "";
    if(index == 0){
      css = "block_0";
    } else if(index == 1){
      css = "block_1";
    } else if(index == 2){
      css = "block_2";
    }
    var poultryid = e.currentTarget.dataset.poultryid;
    this.data.pickRubPoultryId = poultryid;

    // 点击的鸡主人的id
    var userid = e.currentTarget.dataset.userid;
    //当前用户的id
    var myUserId = app.getStorageSync("user_id");
    //当前农场主任的id
    var farmUserId = this.data.farm.userId;

    console.log('userid',userid);
    console.log('myUserId',myUserId);
    console.log('farmUserId',farmUserId);

    if(this.data.is_my == 0){//在好友农场
      if(userid == myUserId){
        this.setData({ 
          clickMy:true,
          showTransition: true,
          transitionCss: css,
        });
      }else{

      }
    }else{//在自己农场
      if(userid != myUserId){
        this.setData({ 
          clickMy:false,
          showTransition: true,
          transitionCss: css,
        });
      }

      if(this.data.farm.bowlWeight == 0){
        Toast.success('今天天气不错，主人~ 我有点饿了呢！')
      }else{
        Toast.success('今天天气不错，主人~ 我正在努力进食中！')
      }
    }
  },
  toFindCk(e){
    var rubFarmerId = e.currentTarget.dataset.rubFarmerId ;
    var that = this;
    fetchApi.httpPost('/farm/infoById', {
      farmId:rubFarmerId,
    }, function (res) {
      console.log("寻找自己的小鸡", res)
      if (res.data.code == 0) {
        var rubFarmerUserId = res.data.data.farm.userId;
        app.globalData.to_farm_user_id = rubFarmerUserId;
        wx.switchTab({
          url: '/pages/farmer/info/index',
        })
      }else{
        Toast.fail(res.data.msg);
      }
    }, function () {})
    
  },
  hideMask(){
    this.data.pickRubPoultryId = 0;
    this.setData({ 
      showTransition: false,
    });
  },
  handleSteal(e){
    var index = parseInt(e.currentTarget.dataset.index);
    var cropId = parseInt(e.currentTarget.dataset.id);
    // Toast.success('点击第' +(index + 1) +"块地")
    this.onHttpStealCrop(cropId);
  },
  /**
   *  偷菜操作
   */
  onHttpStealCrop(crop_id){
    var that = this;
    fetchApi.httpPost('/farm/stealOp', {
      to_user_id: that.data.farmUserId,
      crop_id: crop_id,
    }, function (res) {
      console.log("摘收", res)
      if (res.data.code == 0) {
        Toast.success(res.data.msg);
        that.setData({
          crops: res.data.data.crops,
        })
      }else{
        Toast.fail(res.data.msg);
      }
    }, function () {})
  },
  goLingyang(){
    var that = this;
    var isLogin = app.getStorageSync("isLogin");
    if (!isLogin) {
      wx.navigateTo({
        url: '/pages/login/index?ag_id=' + this.data.ag_id,
      })
    }else{
      wx.navigateTo({
        url: '/pagesFarm/pages/adoption/index',
      })
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var user_id = app.getStorageSync("user_id");
    console.log( "转发成功 user_id",user_id)
    return {
      title: "赶紧来溜小鸡~~",
      path: '/pages/home/home?ag_id='+user_id,
      success: function (res) {
        console.log(res, "转发成功")
      },
      fail: function (res) {
        console.log(res, "转发失败")
      }
    }
  }
})